/* 组件在 layout 布局文件中引用，全局通过redux控制 */

import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Button, Modal, Skeleton } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import loadable from '@loadable/component';
import pMinDelay from 'p-min-delay';

import { setStore } from '@/reducers/common';
import { removeKeyForUrl } from '@/utils';

import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));
const BindPhoneForm = loadable(() => pMinDelay(import('./../BindPhoneForm'), 0), { fallback: <Skeleton paragraph={{rows: 8, width: '100%'}} title={false} active/> });
const BindWxForm = loadable(() => pMinDelay(import('./../BindWxForm'), 0), { fallback: <Skeleton active/> });

/*
    登录、注册成功后，（获取个人信息），获取对话配置
*/
export default props => {
    const initState = () => ({});
    const [state, setState] = useState(initState);
    const { bindVisible, bindType, forceBindPhone=false } = useSelector(s => s.common || {}); // bindType: sms, qrcode
    const dispatch = useDispatch();

    // 取消绑定
    const onBindCancel = () => dispatch(setStore({bindVisible: false, bindType: '', forceBindPhone: false, forceBindOpenId: '', forceBindInviterCode: ''}));

    // 绑定成功
    const onBindOk = (userInfo={}) => {
        dispatch(setStore({userInfo}));
        onBindCancel();

        // 如果强制绑手机号，完事就刷新页面
        forceBindPhone && (location.href = removeKeyForUrl(['code']));
    };

    return (
        <Modal
            open={bindVisible}
            destroyOnHidden={true}
            maskClosable={false}
            closable={false}
            header={null}
            footer={null}
            width={360}
            classNames={{
                content: styles['modal-content'],
                body: styles['modal-body']
            }}
        >
            { forceBindPhone ? null : <Button onClick={onBindCancel} className={styles['close']} type="text" icon={<CloseOutlined/>}></Button> }
            <div className={styles['header']}>
                <div className={styles['t1']}><span><IconFont name={'sms' === bindType ? 'icon-disanfang-weixin' : 'icon-lock_line'}/></span>{'sms' === bindType ? '微信' : '手机'}用户</div>
                <div className={styles['t2']}>绑定{'sms' === bindType ? '手机' : '微信'}，下次可使用{'sms' === bindType ? '手机号码' : '微信扫码'}登录</div>
            </div>
            <div className={styles['form']}>
                {'sms' === bindType ? <BindPhoneForm onOk={onBindOk} /> : null}
                {'qrcode' === bindType ? <BindWxForm onOk={onBindOk} /> : null}
            </div>
        </Modal>
    )
}

